#!/bin/sh -e
#
# /etc/init.d/motioneye: Start the motionEye server
#
### BEGIN INIT INFO
# Provides: motioneye
# Required-Start: $local_fs $syslog $remote_fs $network
# Required-Stop: $remote_fs
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start the motionEye server
# Description: Start the motionEye server
### END INIT INFO

NAME='motioneye'
PATH='/bin:/usr/bin:/sbin:/usr/sbin:/usr/local/bin:/usr/local/sbin'
DAEMON='/usr/local/bin/meyectl'
PIDFILE="/run/$NAME.pid"
DESC='motionEye server'
USER='root'
OPTIONS='startserver -c /etc/motioneye/motioneye.conf -l -b'

. /lib/lsb/init-functions

test -x "$DAEMON" || exit 0

RET=0

case "$1" in
    start)
        log_daemon_msg "Starting $DESC"
	# shellcheck disable=SC2086
        if start-stop-daemon --start --oknodo --exec "$DAEMON" --chuid "$USER" -- $OPTIONS; then
            log_end_msg 0
        else
            log_end_msg 1
            RET=1
        fi
        ;;

    stop)
        log_daemon_msg "Stopping $DESC"
        if start-stop-daemon --stop --oknodo --pidfile "$PIDFILE" --retry 5; then
            log_end_msg 0
        else
            log_end_msg 1
            RET=1
        fi
        ;;

    restart|force-reload)
        log_action_begin_msg "Restarting $DESC"
        if "$0" stop && "$0" start; then
            log_action_end_msg 0
        else
            log_action_cont_msg '(failed)'
            RET=1
        fi
        ;;

    status)
        status_of_proc "$DAEMON" "$NAME"
        ;;

    *)
        echo "Usage: /etc/init.d/$NAME {start|stop|restart|status}"
        RET=1
        ;;
esac

exit "$RET"
